﻿#region Copyright (c) 2010 R. Uittenbosch
/*
* Copyright (C) 2010 R. Uittenbosch
* 
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and 
* associated documentation files (the "Software"), to deal in the Software without restriction, including 
* without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
* copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the 
* following conditions:
* 
* The above copyright notice and this permission notice shall be included in all copies or substantial 
* portions of the Software.
* 
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT 
* LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO 
* EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE 
* USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#endregion

using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Mobile.Mvc;
using Microsoft.Practices.Mobile.ContainerModel;
using TouchUI.System.Mobile.Mvc;
using LinkedService.Mobile.ServiceEntities;
using LinkedService.Mobile;

namespace LinkedIn.Mobile
{
  /// <summary>
  /// Controller for the updatedialog
  /// </summary>
  public class UpdatesController : Controller<LinkedService.Mobile.ServiceEntities.Updates>
  {
    /// <summary>
    /// Notify the view that the updates have been retrieved
    /// </summary>
    [PublishEvent("OnUpdatesLoaded")]
    public event EventHandler UpdatesLoaded;

    /// <summary>
    /// Remember the updates for performance.
    /// </summary>
    private LinkedService.Mobile.ServiceEntities.Updates _updates;

    public UpdatesController(IView<LinkedService.Mobile.ServiceEntities.Updates> view)
      : base(view)
    {

    }

    public Container Container
    {
      get;
      set;
    }

    /// <summary>
    /// The user selected a different profile
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void OnProfileSelected(object sender, PersonEventArgs e)
    {
      if (e.People == null)
        // Navigate to the profile page
        NavigatorService.Navigator.Navigate<ProfileController>(e.Person);
      else
        NavigatorService.Navigator.Navigate<ConnectionsController>(new object[] { e.People });
    }

    // Selected event from the view
    private void OnBack(object sender, EventArgs e)
    {
      NavigatorService.Navigator.GoBack();
    }

    /// <summary>
    /// Group the complete network by date / person / type of update
    /// </summary>
    /// <param name="network"></param>
    /// <returns></returns>
    private Network GroupUpdates(Network network)
    {
      // Create a new network
      Network newNetwork = new Network()
      {
        Updates = new Updates()
        {
          Items = new System.Collections.ObjectModel.Collection<Update>(),
          Start = 0
        }
      };
      // In case no updates where retrieved, return an empty collection
      if (network == null || network.Updates == null || network.Updates.Items == null)
        return newNetwork;

      List<Update> upd = new List<Update>();
      string currentdate = "";
      foreach (Update u in network.Updates.Items)
      {
        string date = UnixTime.FromUnixTime(u.Timestamp / 1000).Date.ToShortDateString();
        // New day?
        if (date != currentdate)
        {
          // update date and add the items to the list
          if (upd.Count != 0)
            upd.ForEach(a => newNetwork.Updates.Items.Add(a));

          // Clear the previous date
          upd.Clear();
          currentdate = date;
        }
        // We do not get the distance back from LinkedIn. But since all updates will come from 1 distance 
        // persons, set the distance to 1
        if (u.UpdateContent.Person != null)
          u.UpdateContent.Person.Distance = 1;

        // Make sure the Updatecontent has a person object
        if (u.UpdateContent.Person == null)
          u.UpdateContent.Person = new Person() { Id = "" };


        // Try to find an existing update of the given person and type
        Update cur = upd.Find(a => a.UpdateContent.Person.Id == u.UpdateContent.Person.Id && a.UpdateType == u.UpdateType);
        if (cur == null)
          upd.Add(u);
        else
        {
          // Should we combine the connections?
          if (cur.UpdateContent.Person.Connections != null)
            cur.UpdateContent.Person.Connections.Items.Add(u.UpdateContent.Person.Connections.Items[0]);
          else
            // Use the last content e.g. last status
            cur.UpdateContent = u.UpdateContent;
        }
      }

     

      // If we have items, add them to the updates list 
      if (upd.Count != 0)
        upd.ForEach(a => newNetwork.Updates.Items.Add(a));     

      // Update the statistics
      newNetwork.Updates.Total            = newNetwork.Updates.Items.Count;
      newNetwork.Updates.NumberOfResults  = newNetwork.Updates.Items.Count;
      return newNetwork;
    }

    /// <summary>
    /// Initialize the controller and the notify the view when we received our data.
    /// </summary>
    /// <param name="parameters"></param>
    protected override void OnInitialize(params object[] parameters)
    {
      if (_updates == null)
      {
        // Get the updates
        LinkedService.Mobile.ServiceEntities.Network n = 
         ApplicationManager.Service.GetNetworkUpdates(
          LinkedService.Mobile.ServiceEntities.NetworkUpdateType.All,
          ApplicationManager.Configuration.GetItem<int>("MaxNrOfUpdates", 50),
          0,
          DateTime.MinValue, 
          DateTime.MinValue);
        _updates = GroupUpdates(n).Updates;
        // Init Model
        this.view.ViewData.Model = _updates;

        // Successful?
        if (!ApplicationManager.Service.Succesfull)
          ApplicationManager.NavigateToErrorHandling();
        else
          // Notify the view
          if (this.UpdatesLoaded != null)
            this.UpdatesLoaded(this, EventArgs.Empty);
      }
    }
  }
}
